﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace AppMain
{
    public class ActionCreator : Singleton<ActionCreator>
    {
        Dictionary<int, EventCreator> pool = new Dictionary<int, EventCreator>();
        Dictionary<int, JsonInfo> cachePool = new Dictionary<int, JsonInfo>();

        delegate IEvent EventCreator(string json);
        EventCreator GetEvent<T, U>() where T : BaseEvent<U>, new() where U : BaseEventData, new()
        {
            return (json) =>
            {
                T t = new T();
                t.setData(JsonConvert.DeserializeObject<U>(json));
                return t;
            };
        }

        protected override void initialize()
        {
            //pool.Add(ActionEventType.Anim, GetEvent<AnimEvent, AnimData>());
            pool.Add(ActionEventType.Attack, GetEvent<AttackEvent, AttackData>());
            //pool.Add(ActionEventType.Effect, GetEvent<EffectEvent, EffectData>());
            pool.Add(ActionEventType.Move, GetEvent<MoveEvent, MoveEventData>());
            //pool.Add(ActionEventType.Audio, GetEvent<AudioEvent, AudioData>());
            pool.Add(ActionEventType.Bullet, GetEvent<BulletEvent, BulletEventData>());
        }

        public static BaseAction createAction(int actionId, DamageData damageData = null)
        {
            BaseAction action = null;
            JsonInfo info;
            if (!Instance.cachePool.TryGetValue(actionId, out info))
            {
                //sql查询
                string sceneSql = string.Format("select *from tb_action_temp where id='{0}'", actionId);
                var Reader = SqlMgr.Instance.select(sceneSql);
                string text = "";
                if (Reader.Read())
                {
                    text = (string)Reader[1];
                }
                Reader.Close();

                if (!string.IsNullOrEmpty(text))
                {
                    info = JsonConvert.DeserializeObject<JsonInfo>(text);
                }
            }
            if (info != null)
            {
                action = new BaseAction(Instance.getEvenes(info).ToArray());
                action.damageData = damageData;
                action.totalTime = info.totalTime;
                action.uid = MathUtils.UniqueID;
                action.id = info.id;
            }
            else
            {
                Logger.logError(string.Format("没有找到Action配置 actionId: {0}", actionId));
            }
            return action;
        }


        List<IEvent> getEvenes(JsonInfo info)
        {
            List<IEvent> events = new List<IEvent>();
            for (int i = 0; i < info.types.Length; i++)
            {
                int type = info.types[i];
                string json = info.jsons[i];
                if (pool.ContainsKey(type))
                {
                    events.Add(pool[type](json));
                }
            }
            return events;
        }

    }
}
